from PyQt6.QtCore import Qt, pyqtSignal, QRectF
from PyQt6.QtGui import QPainter, QAction, QCursor
from PyQt6.QtWidgets import QWidget, QMenu

from gui.utils import FLAG_ALIGN_CENTER
from gui.utils.colors import PALE_TURQUOISE
from gui.utils.size import FILTER_WIDTH, RESOURCE_HEIGHT, ZONING_SIZE, WORLD_SIZE, WINDOW_WIDTH, FILTER_HEIGHT
from state.game_state import GameState
from utils.event_bus import EventBus


class PanelFilter(QWidget):
    def __init__(self, state: GameState, parent=None):
        super(PanelFilter, self).__init__(parent)

        self.state = state
        self.items = ('探索', '领土')

        self.w = FILTER_WIDTH / len(self.items)
        rect = QRectF(WORLD_SIZE, RESOURCE_HEIGHT + ZONING_SIZE, WINDOW_WIDTH - WORLD_SIZE, FILTER_HEIGHT)
        self.setGeometry(rect.toRect())
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)

    def paintEvent(self, event):
        painter = QPainter(self)
        for index, name in enumerate(self.items):
            if index == self.state.filter:
                painter.setBrush(PALE_TURQUOISE)
            else:
                painter.setBrush(Qt.GlobalColor.white)

            rect = QRectF(self.w * index, 0, self.w, FILTER_HEIGHT)
            painter.drawRect(rect)
            painter.drawText(rect, FLAG_ALIGN_CENTER, name)

    def mouseReleaseEvent(self, event):
        pos = event.pos()
        index = int(pos.x() / self.w)

        if event.button() == Qt.MouseButton.LeftButton:
            self.state.filter = index
            EventBus.publish('update_panel_world')
            self.update()
        else:
            self.create_menu(index)

    def create_menu(self, index):
        menu = QMenu(self)

        if index == 0:
            def __reset_resource_display_mode():
                EventBus.publish('update_resource_display', 'resource_details')

            action = QAction('资源', self)
            action.triggered.connect(__reset_resource_display_mode)
            menu.addAction(action)

        menu.popup(QCursor.pos())
